import AuthAPI from "@/api/auth";
import {defineStore} from "pinia"
import {LoginData} from "@/api/auth/model";
import {UserInfo} from "@/api/user/model";
import {TOKEN_KEY} from "@/enums/CacheEnum";
import { resetRouter } from "@/router";
import { store } from "@/stores";

export const useUserStore = defineStore("user", () => {
    const user = ref<UserInfo>({
        roles: [],
        perms: [],
    });

    /**
     * 登录
     *
     * @param {LoginData}
     * @returns
     */
    function login(loginData: LoginData) {
        return new Promise<void>((resolve, reject) => {
            AuthAPI.login(loginData)
                .then((result) => {
                    const {code, msg, data} = result;
                    console.log("登陆结果：", code, msg, data)
                    //将用户登录后获取到的 token 信息保存到浏览器的 localStorage 中，以便后续请求时可以使用这个 token 进行身份验证。
                    localStorage.setItem(TOKEN_KEY, "Bearer " + data);
                    resolve();
                })
                .catch((error) => {
                    reject(error);
                });
        });
    }

    // remove token
    function resetToken() {
        console.log("******  清除 token");
        return new Promise<void>((resolve) => {
            localStorage.removeItem(TOKEN_KEY);
            resetRouter();
            resolve();
        });
    }

    return {
        user,
        login,
        resetToken,
    };
});
// 非setup
export function useUserStoreHook() {
    return useUserStore(store);
}